package practise.tree;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * Created by richard on 5/26/14.
 */
public class TreeAcceptor {
    TreeNode treeNode;
    TreeVisitor visitor;

    public TreeAcceptor(TreeNode treeNode, TreeVisitor visitor) {
        this.treeNode = treeNode;
        this.visitor = visitor;
    }
}

class MidTreeAcceptor extends TreeAcceptor{

    public MidTreeAcceptor(TreeNode treeNode, TreeVisitor visitor) {
        super(treeNode, visitor);
    }
    public void visitAllNode(){
        visitNode(treeNode);
    }

    public void visitNode(TreeNode treeNode1){
        if(treeNode1.getLeft()==null && treeNode1.getRight()==null){
             visitor.accept(treeNode1);
        }
        else{
            visitNode(treeNode1.getLeft());
            visitor.accept(treeNode1);
            visitNode(treeNode1.getRight());
        }
    }
}

class LevelNodeAcceptor extends TreeAcceptor{
    private int level = 0;

    public LevelNodeAcceptor(TreeNode treeNode, TreeVisitor visitor,int level) {
        super(treeNode, visitor);
        this.level = level;
    }

    public void visitAllNode(){
        visitNode(treeNode,level);
    }

    public void visitNode(TreeNode treeNode1, int level){
        if(level==0){
            visitor.accept(treeNode1);
        }
        else{
            visitNode(treeNode1.getLeft(), level - 1);
            visitNode(treeNode1.getRight(),level-1);
        }
    }

    public void visitNodeByWhile(TreeNode treeNode1, int level){
        int currentLevel=0;
        Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
        queue.offer(treeNode1);
        while(currentLevel<level){
            currentLevel++;
            int size = queue.size();
            for(int index=0; index<size ; index++){
                TreeNode treeNode2 = queue.peek();
                queue.offer(treeNode2.getLeft());
                queue.offer(treeNode2.getRight());
            }

        }
        for(TreeNode treeNode2 : queue){
            visitor.accept(treeNode2);
        }

    }

}


